from django.shortcuts import render
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
import logging
from rest_framework import status
from . import constants
from celery_tasks.sms.tasks import send_sms_code

from meiduo_mall.libs.yuntongxun.sms import CCP

logger = logging.getLogger('django')

# Create your views here.
class SMSCodeView(APIView):
    """短信验证码"""

    def get(self, request, mobile):
        #先从redis获取发送标记
        #连接redis
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            #如果取出标记 说明此手机号频繁发短信
            return Response({'message': '手机号频繁发送短信'}, status=status.HTTP_400_BAD_REQUEST)

        #生成验证码 不足六位 随机补充
        sms_code = '%06d' % randint(0, 999999)
        logger.info(f'{sms_code},{mobile}')

        #创建redis管道:把多次redis操作 装入管道 将来一次性去执行 减少redis连接操作
        pl = redis_conn.pipeline()
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        #存储一个标记 此手机号已发送过短信 标记有效期为60s
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        #执行管道
        pl.execute()
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)

        #触发异步任务 异步任务添加celery任务队列
        # send_sms_code(mobile, sms_code) 只是调用函数
        #只有.delay 才能触发异步任务
        send_sms_code.delay(mobile, sms_code)
        return Response({'message': 'ok'})